from zope.interface import Interface
from zope.interface import implements
from zope.component import getMultiAdapter
from Acquisition import aq_inner
from plone.memoize.instance import memoize
from Products.CMFCore.utils import getToolByName

from plone.app.portlets.portlets import base
from plone.portlets.interfaces import IPortletDataProvider

from zope import schema
from zope.formlib import form
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile

from my315ok.xtinfocontent import xtinfocontentMessageFactory as _
from plone.portlet.collection import PloneMessageFactory as _a
from my315ok.xtinfocontent.interfaces.navlink import Inavlink

class Inavlink_portlet(IPortletDataProvider):
    """A portlet

    It inherits from IPortletDataProvider because for this portlet, the
    data that is being rendered and the portlet assignment itself are the
    same.
    """

    # TODO: Add any zope.schema fields here to capture portlet configuration
    # information. Alternatively, if there are no settings, leave this as an
    # empty interface - see also notes around the add form and edit form
    # below.

    # some_field = schema.TextLine(title=_(u"Some field"),
    #                              description=_(u"A field to use"),
    #                              required=True)
    name = schema.TextLine(
           title=_(u"navlink_title", default=u"Title"),
           description=_(u"navigation_link_title",
                         default=u"a title for this navigation link zone"),
           default=u"",
           required=False)
    cssclass = schema.TextLine(
           title=_(u"navlink class"),
           description=_(u""),
           default=u"",
           required=False)
    limit = schema.Int(title=_a(u"Limit"),
                       description=_a(u"Specify the maximum number of items to show in the portlet. "
                                       "Leave this blank to show all items."),
                       required=False)
    rows = schema.Int(title=_(u"rows"),
                       description=_(u"Specify the rows number for navlink portlet table."),
                       required=True)
    cols = schema.Int(title=_(u"cols"),
                       description=_(u"Specify the cols number for per row of the table."),
                       required=True)
#    tag = schema
    tag = schema.Tuple(title=_(u"nav link tag"),
           description=_(u"specify the tag for select  navlink"),
           required=True,
           value_type=schema.Choice(
                                    vocabulary="my315ok.xtinfocontent.navtag"))
     


class Assignment(base.Assignment):
    """Portlet assignment.

    This is what is actually managed through the portlets UI and associated
    with columns.
    """

    implements(Inavlink_portlet)

    # TODO: Set default values for the configurable parameters here

    # some_field = u""

    # TODO: Add keyword parameters for configurable parameters here
    # def __init__(self, some_field=u''):
    #    self.some_field = some_field

    def __init__(self,name=u'',cssclass='',limit=None,rows=None,cols=None,tag=None):
        self.name = name
        self.cssclass = cssclass
        self.limit = limit
        self.rows = rows
        self.cols = cols
        self.tag = tag
        

    @property
    def title(self):
        """This property is used to give the title of the portlet in the
        "manage portlets" screen.
        """
        return _(u"NavLinkPortlet")


class Renderer(base.Renderer):
    """Portlet renderer.

    This is registered in configure.zcml. The referenced page template is
    rendered, and the implicit variable 'view' will refer to an instance
    of this class. Other methods can be added and referenced in the template.
    """

    render = ViewPageTemplateFile('navlink_portlet.pt')
    def header(self):
        return self.data.name
    def rows(self):
        return self.data.rows
    def cols(self):
        return self.data.cols
    def size(self):
        t = self.data.limit
        filter = len(self.filternav())
        if t > 0 and t < filter:
            return t
        else:
            return filter
    def rowtag(self):
        c = self.cols()
        size = self.size()        
        return range(int((size + c - 1)/c)) 
    def coltag(self):
        c = self.cols()               
        return range(c) 
    def css(self):
        return self.data.cssclass  
    
    def islogo(self,brain):
        url = brain.getURL()
        imgurl = url + "/iconimage_mini" 
        context = aq_inner(self.context)
        portal_state = getMultiAdapter((context, self.request), name=u'plone_portal_state')
        portal = portal_state.portal()        
        tmp = portal.unrestrictedTraverse(imgurl, default=None)
        if tmp is None:
            return False
        else:
            return True
        
    def add_paras(self,brain):
##        import pdb
##        pdb.set_trace()
        item={}
        url = brain.getURL()
        item['title'] = brain.Title
        item['link'] = brain.link
        if self.islogo(brain):        
            item['img_url'] = url + "/iconimage_mini"
        else:
            item['img_url'] = ''
        return item
    
    def filternav(self):
        context = aq_inner(self.context)
        catalog = getToolByName(context, 'portal_catalog')
        curtag = self.data.tag
        result = []
        if curtag is not None:
            brains = catalog(object_provides=Inavlink.__identifier__,
                        tag=curtag)
        else:
             brains = catalog(object_provides=Inavlink.__identifier__)
        return brains
            
        
    @memoize
    def fetch_navlink(self):
#        import pdb
#        pdb.set_trace()

        brains = self.filternav()
        result = []     
        for b in brains:
            theob = self.add_paras(b)
            result.append(theob)
                
        return result  
            
    
    


# NOTE: If this portlet does not have any configurable parameters, you can
# inherit from NullAddForm and remove the form_fields variable.

class AddForm(base.AddForm):
    """Portlet add form.

    This is registered in configure.zcml. The form_fields variable tells
    zope.formlib which fields to display. The create() method actually
    constructs the assignment that is being added.
    """
    form_fields = form.Fields(Inavlink_portlet)

    def create(self, data):
        return Assignment(**data)


# NOTE: IF this portlet does not have any configurable parameters, you can
# remove this class definition and delete the editview attribute from the
# <plone:portlet /> registration in configure.zcml

class EditForm(base.EditForm):
    """Portlet edit form.

    This is registered with configure.zcml. The form_fields variable tells
    zope.formlib which fields to display.
    """
    form_fields = form.Fields(Inavlink_portlet)
